﻿using Models.ApiModel;
using Models.ApiModel.req;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Security;
using Tools;
using WHC.Framework.Commons;

namespace webui
{
    public class VerifyKeyAttribute : AuthorizationFilterAttribute
    {
        /// <summary>
        /// 验证方法 - 在 ActionExcuting过滤器之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes<VerifyKeyAttribute>().Any() || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<VerifyKeyAttribute>().Any())
            {
                var authValue = actionContext.Request.Headers.Authorization;  //actionContext：Action方法请求上下文
                var auther = actionContext.Request.Headers.Authorization;

                if (auther == null)
                {
                    //actionContext.Response.ReasonPhrase = "登录已过期，请重新登录";
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                        new BaseRes { Msg = "无登录数据，请登录", Code = 0 });
                    //HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
                }
                else
                {

                    if (auther.Scheme == "Basic" &&  !string.IsNullOrEmpty(auther.Parameter)  )
                    {
                        string userstr = Base64Util.Decrypt(auther.Parameter);
                       
                        Token user = userstr.ToObject<Token>(); 
                        if (user == null || string.IsNullOrEmpty(user.RoleName) || user.Userid==0 )
                        {
                            //actionContext.Response.ReasonPhrase = "登录已过期，请重新登录";
                            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                                new { Msg = "登录参数不合法已过期，请重新登录", Code = 0 });
                            // HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
                             
                        }
                        else
                        {
                            //验证时间
                        long curent =    DateTimeHelper.ConvertTimeToJS(DateTime.Now);
                            if (curent>user.ExprTime)
                            {
                                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                               new { Msg = "登录已过期，请重新登录", Code = 0 });
                            }

                            //修改API接口参数
                            actionContext.ActionArguments["UserName"] = user.UserName;
                            actionContext.ActionArguments["Userid"] = user.Userid;
                            actionContext.ActionArguments["RoleName"] = user.RoleName;
                            //if (actionContext.ActionArguments.ContainsKey("accounType"))
                            //{ 
                            //    actionContext.ActionArguments["UserName"] = userData.UserName; ;
                            //}
                        }


                    }
                    return;
                }


                //1.验证Key 

                //BaseRes response = new BaseRes();
                ////1. 校验key 。 
                //var stream = ((HttpContextBase)actionContext.Request.Properties["MS_HttpContext"]).Request.InputStream;
                //StreamReader reader = new StreamReader(stream);
                //string text = reader.ReadToEnd();
                //dynamic result = null;
                //if (!string.IsNullOrEmpty(text))
                //{
                //    result = JObject.Parse(text);
                //}
                //else
                //{
                //    return;
                //}
                //response.Code = 0;
                //response.CodeMsg = "key未填写，无权限访问";

                //try
                //{
                //    if (result.Key == null)
                //    {
                //        actionContext.Response = actionContext.Request.CreateResponse(response);
                //        return;
                //    }
                //}
                //catch (Exception)
                //{

                //    actionContext.Response = actionContext.Request.CreateResponse(response);
                //    return;
                //}

                //if (string.IsNullOrEmpty(result.Key.Value))
                //{

                //    response.CodeMsg = "key不正确，无权限访问";
                //    actionContext.Response = actionContext.Request.CreateResponse(response);
                //    return;
                //}
                //var keymodel = new APIOdoorSupplierBLL().GetModeP2P_AppKey(result.Key.Value);
                //if (keymodel == null)
                //{
                //    response.CodeMsg = "key不正确，无权限访问";
                //    actionContext.Response = actionContext.Request.CreateResponse(response);
                //    return;
                //}
                //return;

            }

        }



    }
}